<template>
  <div class="analysis-card">
    <h3 class="analysis-title customer-title">用户画像预测分析</h3>
    <div class="charts-grid">
      <div class="charts-row">
        <div class="chart-section">
          <span class="chart-title">预测性别</span>
          <div ref="pieChartRefCustomerSex" class="pie-chart"></div>
        </div>
        <div class="chart-section">
          <span class="chart-title">预测年龄段</span>
          <div ref="pieChartRefCustomerAge" class="pie-chart"></div>
        </div>
      </div>
      <div class="charts-row">
        <div class="chart-section">
          <span class="chart-title">预测下单城市</span>
          <div ref="pieChartRefCustomerCity" class="pie-chart"></div>
        </div>
        <div class="chart-section">
          <span class="chart-title">预测消费力</span>
          <div ref="pieChartRefCustomerConsumption" class="pie-chart"></div>
        </div>
      </div>
    </div>
    <div class="eight-groups">
      <span class="chart-title">八大消费人群</span>
      <div ref="pieChartRefCustomerEight" class="pie-chart-large"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import type { ReportSection, ReportItem } from '@/types/report'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  LabelLayout,
  CanvasRenderer
])

interface Props {
  sectionData: ReportSection
}

const props = defineProps<Props>()

// 图表引用
const pieChartRefCustomerSex = ref<HTMLElement | null>(null)
const pieChartRefCustomerAge = ref<HTMLElement | null>(null)
const pieChartRefCustomerCity = ref<HTMLElement | null>(null)
const pieChartRefCustomerConsumption = ref<HTMLElement | null>(null)
const pieChartRefCustomerEight = ref<HTMLElement | null>(null)

let chartInstances: echarts.ECharts[] = []

type ChartDataType = {
  性别: { [key: string]: number };
  年龄段: { [key: string]: number };
  城市: { [key: string]: number };
  消费力: { [key: string]: number };
  消费人群: { [key: string]: number };
}

// 默认数据
const defaultData: ChartDataType = {
  '性别': {
    '男': 60,
    '女': 40
  },
  '年龄段': {
    '18-25岁': 30,
    '26-35岁': 45,
    '36-45岁': 15,
    '46岁以上': 10
  },
  '城市': {
    '一线城市': 40,
    '二线城市': 35,
    '三线城市': 15,
    '其他': 10
  },
  '消费力': {
    '高': 20,
    '中高': 30,
    '中': 35,
    '低': 15
  },
  '消费人群': {
    '品质追求者': 25,
    '精打细算者': 20,
    '潮流引领者': 15,
    '理性消费者': 12,
    '冲动消费者': 10,
    '实用主义者': 8,
    '品牌忠实者': 6,
    '其他': 4
  }
}

// 初始化饼图配置
const initPieChart = (data: Record<string, number>) => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    grid: {
      containLabel: true,
      top: 5,
      bottom: 5
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      left: '5%',
      top: 'center',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 4,
      textStyle: {
        color: '#4a5568',
        fontSize: '11px',
        lineHeight: 13,
        padding: [1, 0, 1, 0],
        width: 60,
        overflow: 'breakAll'
      }
    },
    series: [{
      type: 'pie',
      radius: ['32%', '58%'],
      center: ['65%', '50%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 2,
        borderColor: '#fff',
        borderWidth: 1
      },
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      data: Object.entries(data).map(([name, value]) => ({
        name,
        value
      }))
    }]
  }
}

// 八大消费人群饼图配置
const initEightGroupsChart = (data: Record<string, number>) => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      left: '5%',
      top: 'center',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 4,
      textStyle: {
        color: '#4a5568',
        fontSize: '11px',
        lineHeight: 13,
        padding: [1, 0, 1, 0],
        width: 80,
        overflow: 'breakAll'
      }
    },
    series: [{
      type: 'pie',
      radius: '52%',
      center: ['65%', '50%'],
      data: Object.entries(data).map(([name, value]) => ({
        name,
        value
      }))
    }]
  }
}

// 初始化图表的函数
const initChart = (el: HTMLElement, option: any) => {
  const chart = echarts.init(el, undefined, {
    renderer: 'canvas',
    useDirtyRect: false
  })
  chart.setOption(option)
  
  // 使用防抖处理resize
  let resizeTimeout: NodeJS.Timeout
  const observer = new ResizeObserver(() => {
    clearTimeout(resizeTimeout)
    resizeTimeout = setTimeout(() => {
      chart.resize()
    }, 100)
  })
  observer.observe(el)
  
  return chart
}

// 获取真实数据或默认数据
const getChartData = (key: keyof ChartDataType): Record<string, number> => {
  const realData = props.sectionData.items.find((item: ReportItem) => item.name === key)?.value
  return (realData as Record<string, number>) || defaultData[key]
}

// 初始化所有图表
onMounted(() => {
  nextTick(() => {
    // 性别分布
    if (pieChartRefCustomerSex.value) {
      const chart = initChart(pieChartRefCustomerSex.value, initPieChart(getChartData('性别')))
      chartInstances.push(chart)
    }

    // 年龄分布
    if (pieChartRefCustomerAge.value) {
      const chart = initChart(pieChartRefCustomerAge.value, initPieChart(getChartData('年龄段')))
      chartInstances.push(chart)
    }

    // 城市分布
    if (pieChartRefCustomerCity.value) {
      const chart = initChart(pieChartRefCustomerCity.value, initPieChart(getChartData('城市')))
      chartInstances.push(chart)
    }

    // 消费力分布
    if (pieChartRefCustomerConsumption.value) {
      const chart = initChart(pieChartRefCustomerConsumption.value, initPieChart(getChartData('消费力')))
      chartInstances.push(chart)
    }

    // 八大消费人群
    if (pieChartRefCustomerEight.value) {
      const chart = initChart(pieChartRefCustomerEight.value, initEightGroupsChart(getChartData('消费人群')))
      chartInstances.push(chart)
    }
  })
})

// 组件销毁时清理
onUnmounted(() => {
  chartInstances.forEach(chart => chart.dispose())
})
</script>

<style scoped>
.analysis-card {
  margin-bottom: 12px;
  padding: 12px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.customer-title {
  font-size: 15px;
  color: #2d3748;
  font-weight: 600;
  margin-bottom: 8px;
  padding-bottom: 4px;
  border-bottom: 2px solid #e2e8f0;
}

.charts-grid {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.charts-row {
  display: flex;
  gap: 6px;
  width: 100%;
}

.chart-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
  min-height: 180px;
}

.chart-title {
  font-size: 12px;
  font-weight: bold;
  color: #333;
}

.pie-chart {
  flex: 1;
  height: 180px;
  width: 100%;
  background: #f8fafc;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
}

.pie-chart-large {
  height: 220px;
  width: 100%;
  background: #f8fafc;
  border-radius: 6px;
  margin-top: 6px;
  position: relative;
  overflow: hidden;
}

.pie-chart > div,
.pie-chart-large > div {
  position: relative !important;
  width: 100% !important;
  height: 100% !important;
}

.eight-groups {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #ededed;
}

@media (max-width: 768px) {
  .charts-row {
    flex-direction: column;
  }
}
</style> 